# uncompyle6 version 3.2.3
# Python bytecode 3.6 (3379)
# Decompiled from: Python 3.6.8 |Anaconda custom (64-bit)| (default, Feb 21 2019, 18:30:04) [MSC v.1916 64 bit (AMD64)]
# Embedded file name: helpers\json_extra\__init__.py
__author__ = "sanyi"
import json
from datetime import datetime, date
from uuid import UUID


class JsonEncoder(json.JSONEncoder):
    """
    Extending the default JsonEncoder type support
    """

    def default(self, obj):
        try:
            return obj.to_dict()
        except AttributeError:
            pass

        if isinstance(obj, (datetime, date)):
            return obj.isoformat()
        if isinstance(obj, UUID):
            return str(obj)
            try:
                return json.JSONEncoder.default(self, obj)
            except Exception:
                return repr(obj)


def json_iter_encoder(data, min_chunk_length=4096, encoder_class=JsonEncoder):
    """
    Generator for packing up small chunks yielded by the JsonEncoder to min_chunk_length
    pywsgi server create a HTTP chunks for each yield, while some data will be serialized in very small chunks,
    we try to avoid this.
    
    :param data: the data to be serialized
    :param min_chunk_length: the minimum chunk length we want to buffer before yielding
    :param encoder_class: the JsonEncoder encoder class, default is the extended one provided in this module
    :return: None (yields binary strings)
    """
    output = []
    len_output = 0
    for x in (encoder_class(indent=1)).iterencode(data):
        chunk = x.encode("utf-8")
        len_output += len(chunk)
        output.append(chunk)
        if len(output) >= min_chunk_length:
            yield (b"").join(output)
            output = []
            len_output = 0

    if output:
        yield (b"").join(output)
